package com.eorchis.module.trainingclass.service.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eorchis.constants.RoleConstants;
import com.eorchis.core.basedao.dao.IDaoSupport;
import com.eorchis.core.basedao.entity.IBaseEntity;
import com.eorchis.core.basedao.entity.impl.AbstractBaseEntity;
import com.eorchis.core.service.impl.AbstractBaseService;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ICommond;
import com.eorchis.log.LogRecord;
import com.eorchis.log.LogRecordParam;
import com.eorchis.log.LogThread;
import com.eorchis.module.TrainingConstants;
import com.eorchis.module.basedata.domain.BaseData;
import com.eorchis.module.basedata.service.cache.BaseDataCacheUtil;
import com.eorchis.module.classauditinfo.dao.IClassAuditInfoDao;
import com.eorchis.module.classauditinfo.ui.commond.ClassAuditInfoQueryCommond;
import com.eorchis.module.classauditinfo.ui.commond.ClassAuditInfoValidCommond;
import com.eorchis.module.classcourse.dao.IClassCourseDao;
import com.eorchis.module.classcourse.querybean.ClassCourseQueryBean;
import com.eorchis.module.classcourse.service.IClassCourseService;
import com.eorchis.module.classcourse.ui.commond.ClassCourseQueryCommond;
import com.eorchis.module.classdept.service.IClassDeptService;
import com.eorchis.module.classdept.ui.commond.ClassDeptValidCommond;
import com.eorchis.module.classuser.dao.IClassUserDao;
import com.eorchis.module.classuser.domain.ClassUser;
import com.eorchis.module.classuser.domain.ClassUserQueryBean;
import com.eorchis.module.classuser.domain.DepartmentUserBean;
import com.eorchis.module.classuser.ui.commond.ClassUserQueryCommond;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.department.domain.DepartmentTreeCondition;
import com.eorchis.module.department.ui.commond.DepartmentValidCommond;
import com.eorchis.module.exceluitls.ReadExcelUtils;
import com.eorchis.module.exceluitls.domain.excel.ExcelCell;
import com.eorchis.module.exceluitls.domain.excel.ExcelRow;
import com.eorchis.module.exceluitls.domain.excel.ExcelSheet;
import com.eorchis.module.preauthorizationregistration.service.IPreAuthorizationRegistrationService;
import com.eorchis.module.preauthorizationregistration.ui.commond.PreAuthorizationRegistrationQueryCommond;
import com.eorchis.module.preauthorizationregistration.ui.commond.PreAuthorizationRegistrationValidCommond;
import com.eorchis.module.signupdept.service.ISignupDeptService;
import com.eorchis.module.signupdept.ui.commond.SignupDeptQueryCommond;
import com.eorchis.module.signupdept.ui.commond.SignupDeptValidCommond;
import com.eorchis.module.trainingclass.dao.ITrainingClassDao;
import com.eorchis.module.trainingclass.domain.BaseAttachment;
import com.eorchis.module.trainingclass.domain.BaseUserBean;
import com.eorchis.module.trainingclass.domain.ClassScopeDepartment;
import com.eorchis.module.trainingclass.domain.ClassSignUpDepartment;
import com.eorchis.module.trainingclass.domain.SyncTrainingClassQueryBean;
import com.eorchis.module.trainingclass.domain.TrainingClass;
import com.eorchis.module.trainingclass.domain.TrainingClassPartFieldUpdateBean;
import com.eorchis.module.trainingclass.domain.UserIdAndYear;
import com.eorchis.module.trainingclass.querybean.TrainingClassQueryBean;
import com.eorchis.module.trainingclass.service.ITrainingClassService;
import com.eorchis.module.trainingclass.ui.commond.TrainingClassQueryCommond;
import com.eorchis.module.trainingclass.ui.commond.TrainingClassValidCommond;
import com.eorchis.module.user.domain.User;
import com.eorchis.util.Base64Util;
import com.eorchis.util.UniteConstants;
import com.eorchis.utils.DateUtil;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: TrainingClassServiceImpl<br>
 * Description: 培训班信息管理业务接口实现<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * 
 * @author Max
 * @createDate 2013-12-10
 * @version $Revision$
 */
// 声明本类为Server实现类，声明bean名称
@Service(value = "com.eorchis.module.trainingclass.service.impl.TrainingClassServiceImpl")
public class TrainingClassServiceImpl extends AbstractBaseService implements ITrainingClassService {

	@Autowired
	@Qualifier("com.eorchis.module.trainingclass.dao.impl.TrainingClassDaoImpl")
	private ITrainingClassDao trainingClassDao;

	@Resource(name = "com.eorchis.module.basedata.service.cache.BaseDataCacheUtil")
	private BaseDataCacheUtil baseDataCacheUtil;

	@Resource(name = "com.eorchis.module.classuser.dao.impl.ClassUserDaoImpl")
	private IClassUserDao classUserDao;

	// 班级课程维护接口
	@Autowired
	@Qualifier("com.eorchis.module.classcourse.service.impl.ClassCourseServiceImpl")
	private IClassCourseService classCourseService;

	@Autowired
	@Qualifier("com.eorchis.module.classauditinfo.dao.impl.ClassAuditInfoDaoImpl")
	private IClassAuditInfoDao classAuditInfoDao;

	@Autowired
	@Qualifier("com.eorchis.module.classdept.service.impl.ClassDeptServiceImpl")
	private IClassDeptService classDeptService;
	// 报名单位接口
	@Autowired
	@Qualifier("com.eorchis.module.signupdept.service.impl.SignupDeptServiceImpl")
	private ISignupDeptService signupDeptService;

	@Autowired
	@Qualifier("com.eorchis.module.classcourse.dao.impl.ClassCourseDaoImpl")
	private IClassCourseDao classCourseDao;

	/**
	 * 报名预授权
	 */
	@Autowired
	@Qualifier("com.eorchis.module.preauthorizationregistration.service.impl.PreAuthorizationRegistrationServiceImpl")
	IPreAuthorizationRegistrationService preAuthorizationRegistrationService;

	public IDaoSupport getDaoSupport() {
		return trainingClassDao;
	}

	@SuppressWarnings("unchecked")
	public TrainingClassValidCommond toCommond(IBaseEntity entity) {
		return new TrainingClassValidCommond((TrainingClass) entity);
	}

	@Autowired
	private ReadExcelUtils excelUtils;

	/**
	 * 根据查询条件获取专题班信息
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-11
	 */
	@Override
	public List<TrainingClassQueryBean> findThematicClassList(TrainingClassQueryCommond commond) throws Exception {
		List<TrainingClassQueryBean> list = this.trainingClassDao.findTrainingClassList2(commond);
		if (list != null && list.size() > 0) {
			String[] ids = new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				TrainingClassQueryBean bean = list.get(i);
				bean.setReportedNumStr(bean.getReportedNumber().toString() + "/" + bean.getReportedNum().toString());
				ids[i] = bean.getClassId();
			}

			ClassAuditInfoQueryCommond qCommond = new ClassAuditInfoQueryCommond();
			qCommond.setSearchClassIds(ids);
			Map<String, String> result = classAuditInfoDao.getAuditReson(qCommond);

			for (int i = 0; i < list.size(); i++) {
				if (result.get(list.get(i).getClassId()) != null) {
					String audit = result.get(list.get(i).getClassId());
					list.get(i).setAuditReason(audit);
				}
			}
		}
		return list;
	}
	
	/**
	 * 根据查询条件获取专题班信息
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-11
	 */
	@Override
	public List<TrainingClassQueryBean> findThematicClassList2(TrainingClassQueryCommond commond) throws Exception {
		List<TrainingClassQueryBean> list = this.trainingClassDao.findTrainingClassList2(commond);
		if (list != null && list.size() > 0) {
			String[] ids = new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				TrainingClassQueryBean bean = list.get(i);
				bean.setReportedNumStr(bean.getReportedNumber().toString() + "/" + bean.getReportedNum().toString());
				ids[i] = bean.getClassId();
			}
			
			ClassAuditInfoQueryCommond qCommond = new ClassAuditInfoQueryCommond();
			qCommond.setSearchClassIds(ids);
			Map<String, String> result = classAuditInfoDao.getAuditReson(qCommond);
			
			for (int i = 0; i < list.size(); i++) {
				if (result.get(list.get(i).getClassId()) != null) {
					String audit = result.get(list.get(i).getClassId());
					list.get(i).setAuditReason(audit);
				}
			}
		}
		return list;
	}

	/**
	 * 根据查询条件获取专题班信息(报名用)
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-11
	 */
	@Override
	public List<TrainingClassQueryBean> findThematicClassListSignUp(TrainingClassQueryCommond commond) throws Exception {
		List<TrainingClassQueryBean> list = this.trainingClassDao.findTrainingClassListSignUp(commond);
		if (list != null && list.size() > 0) {
			String[] ids = new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				TrainingClassQueryBean bean = list.get(i);
				bean.setReportedNumStr(bean.getReportedNumber().toString() + "/" + bean.getReportedNum().toString());
				ids[i] = bean.getClassId();
			}

			ClassAuditInfoQueryCommond qCommond = new ClassAuditInfoQueryCommond();
			qCommond.setSearchClassIds(ids);
			Map<String, String> result = classAuditInfoDao.getAuditReson(qCommond);

			for (int i = 0; i < list.size(); i++) {
				if (result.get(list.get(i).getClassId()) != null) {
					String audit = result.get(list.get(i).getClassId());
					list.get(i).setAuditReason(audit);
				}
			}
		}
		return list;
	}
	
	/**
	 * 根据查询条件获取专题班信息(报名用)
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-11
	 */
	@Override
	public List<TrainingClassQueryBean> findThematicClassListSignUp2(TrainingClassQueryCommond commond) throws Exception {
		List<TrainingClassQueryBean> list = this.trainingClassDao.findTrainingClassListSignUp2(commond);
		if (list != null && list.size() > 0) {
			String[] ids = new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				TrainingClassQueryBean bean = list.get(i);
				bean.setReportedNumStr(bean.getReportedNumber().toString() + "/" + bean.getReportedNum().toString());
				ids[i] = bean.getClassId();
			}
			
			ClassAuditInfoQueryCommond qCommond = new ClassAuditInfoQueryCommond();
			qCommond.setSearchClassIds(ids);
			Map<String, String> result = classAuditInfoDao.getAuditReson(qCommond);
			
			for (int i = 0; i < list.size(); i++) {
				if (result.get(list.get(i).getClassId()) != null) {
					String audit = result.get(list.get(i).getClassId());
					list.get(i).setAuditReason(audit);
				}
			}
		}
		return list;
	}

	/**
	 * 根据查询条件获取专题班信息
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author GaoGQ
	 * @date 2015-03-26
	 */
	@Override
	public List<TrainingClassQueryBean> findThematicClassListFinish(TrainingClassQueryCommond commond) throws Exception {
		List<TrainingClassQueryBean> list = this.trainingClassDao.findTrainingClassListFinish(commond);
		if (list != null && list.size() > 0) {
			String[] ids = new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				ids[i] = list.get(i).getClassId();
			}

			ClassAuditInfoQueryCommond qCommond = new ClassAuditInfoQueryCommond();
			qCommond.setSearchClassIds(ids);
			Map<String, String> result = classAuditInfoDao.getAuditReson(qCommond);

			for (int i = 0; i < list.size(); i++) {
				if (result.get(list.get(i).getClassId()) != null) {
					String audit = result.get(list.get(i).getClassId());
					list.get(i).setAuditReason(audit);
				}
			}
		}

		return list;
	}

	/**
	 * 根据查询条件获取专题班信息
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-23
	 */
	@Override
	public List<TrainingClassQueryBean> findTrainingClassListForUnitPorject(TrainingClassQueryCommond commond) throws Exception {
		return this.trainingClassDao.findTrainingClassListForUnitProject(commond);
	}

	/**
	 * 更新班级状态 启用/作废、 发布/未发布、上报
	 * 
	 * @param trainingClassPartFieldUpdateBean
	 * @throws Exception
	 * @author ZhaoQT
	 * @date 2013-12-17
	 */
	@Override
	public void updateTrainingClassState(TrainingClassPartFieldUpdateBean trainingClassPartFieldUpdateBean) throws Exception {
		TrainingClassQueryCommond trainingClassQueryCommond = (TrainingClassQueryCommond) trainingClassPartFieldUpdateBean.getiQueryCommond();
		TrainingClassValidCommond trainingClassValidCommond = (TrainingClassValidCommond) trainingClassPartFieldUpdateBean.getiCommond();
		if (PropertyUtil.objectNotEmpty(trainingClassQueryCommond) && PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSearchUpdateClassIds())) {
			Map<String, Object> fieldValue = new HashMap<String, Object>();
			// 组装更新属性
			if (trainingClassValidCommond != null) {
				if (PropertyUtil.objectNotEmpty(trainingClassValidCommond.getActiveState())) {
					fieldValue.put("activeState", trainingClassValidCommond.getActiveState());
					// 删除课程操作
					if (trainingClassValidCommond.getActiveState().equals(TrainingClass.IS_ACTIVE_N)) {
						classCourseDao.deleteCourseByClassIds(trainingClassQueryCommond.getSearchUpdateClassIds());
					}
				}
				if (PropertyUtil.objectNotEmpty(trainingClassValidCommond.getPublishState())) {
					fieldValue.put("publishState", trainingClassValidCommond.getPublishState());
					fieldValue.put("allotDeptState", TrainingClass.IS_ALLOTDEPT_Y);// 单位发布的时候要触发
																					// 分配单位的确定状态
				}
				if (PropertyUtil.objectNotEmpty(trainingClassValidCommond.getReportState())) {
					fieldValue.put("reportState", trainingClassValidCommond.getReportState());
					fieldValue.put("reportDate", new Date());
				}
				// if(PropertyUtil.objectNotEmpty(trainingClassValidCommond.getEndState()))
				// {
				// fieldValue.put("endState",
				// trainingClassValidCommond.getEndState());
				// }
				if (PropertyUtil.objectNotEmpty(trainingClassValidCommond.getAuditState())) {
					fieldValue.put("auditState", trainingClassValidCommond.getAuditState());
					fieldValue.put("auditDate", new Date());
				}
				if (PropertyUtil.objectNotEmpty(trainingClassValidCommond.getLatestOperateDate())) {
					fieldValue.put("latestOperateDate", trainingClassValidCommond.getLatestOperateDate());
					fieldValue.put("lastOperateTime", trainingClassValidCommond.getLatestOperateDate());
					//fieldValue.put("auditDate", new Date());
				}
			}
			/*
			 * 添加班级状态和报名状态的判断: 1、只要是未发布的班级状态就是未开班 2、只要是未发布的报名状态就是未开始报名
			 * 3、已发布且已开班的报名状态就是报名结束
			 */
			if (PropertyUtil.objectNotEmpty(trainingClassValidCommond.getPublishState()) && (TrainingClass.IS_PUBLISH_N == trainingClassValidCommond.getPublishState())) {
				// (已发布修改成未发布时可以同时批量更新发布状态、班级状态、报名状态)
				// 未开班
				fieldValue.put("openState", TrainingClass.IS_OPENSTATE_N);
				// 报名未开始
				fieldValue.put("signUpState", TrainingClass.IS_SIGNUP_N);

				trainingClassPartFieldUpdateBean.setFieldValue(fieldValue);
				// 执行底层更新
				trainingClassDao.updateTrainingClassPartField(trainingClassPartFieldUpdateBean, null);
			} else {// (未发布修改成已发布时，需要分别判断发布状态、班级状态、报名状态)
				if (PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSearchUpdateClassIds())) {
					String[] searchUpdateClassIds = trainingClassQueryCommond.getSearchUpdateClassIds();
					for (String classId : searchUpdateClassIds) {
						// 根据id查询班级信息
						TrainingClassValidCommond tValidCommond = (TrainingClassValidCommond) this.find(classId);
//						tValidCommond.setEndDate(DateUtil.changeDate23H59m59s999ms(tValidCommond.getEndDate()));
						// 班级状态判断
						// 已结班
						if (PropertyUtil.objectNotEmpty(tValidCommond.getEndDate()) && compare_date_end(tValidCommond.getEndDate()) < 0) {
							fieldValue.put("openState", TrainingClass.IS_ENDSTATE_Y);
							tValidCommond.setOpenState(TrainingClass.IS_ENDSTATE_Y);
							// 已开班
						} else if (PropertyUtil.objectNotEmpty(tValidCommond.getBeginDate()) && compare_date(tValidCommond.getBeginDate()) <= 0) {
							fieldValue.put("openState", TrainingClass.IS_OPENSTATE_Y);
							tValidCommond.setOpenState(TrainingClass.IS_OPENSTATE_Y);
							// 未开班
						} else if (PropertyUtil.objectNotEmpty(tValidCommond.getBeginDate()) && compare_date(tValidCommond.getBeginDate()) > 0) {
							fieldValue.put("openState", TrainingClass.IS_OPENSTATE_N);
							tValidCommond.setOpenState(TrainingClass.IS_OPENSTATE_N);
						}
						// 报名状态判断
						if (PropertyUtil.objectNotEmpty(tValidCommond.getOpenState()) && (TrainingClass.IS_OPENSTATE_Y == tValidCommond.getOpenState())) {
							// 报名结束
							fieldValue.put("signUpState", TrainingClass.IS_SIGNUP_END);
						} else {
							// 报名结束
							if (PropertyUtil.objectNotEmpty(tValidCommond.getEnterEndTime()) && compare_date(tValidCommond.getEnterEndTime()) < 0)
								fieldValue.put("signUpState", TrainingClass.IS_SIGNUP_END);
							// 正在报名
							else if (PropertyUtil.objectNotEmpty(tValidCommond.getEnterBeginTime()) && compare_date(tValidCommond.getEnterBeginTime()) <= 0)
								fieldValue.put("signUpState", TrainingClass.IS_SIGNUP_BEGIN);
							// 报名未开始
							else if (PropertyUtil.objectNotEmpty(tValidCommond.getEnterBeginTime()) && compare_date(tValidCommond.getEnterBeginTime()) > 0)
								fieldValue.put("signUpState", TrainingClass.IS_SIGNUP_N);
						}
						trainingClassPartFieldUpdateBean.setFieldValue(fieldValue);
						// 执行底层更新
						trainingClassDao.updateTrainingClassPartField(trainingClassPartFieldUpdateBean, classId);
					}
				}
			}
			// 添加记录日志的逻辑 add by NingSS at 20150504
			// LogRecordParam param = new LogRecordParam();
			// List<LogRecordParam> paramList = new ArrayList<LogRecordParam>();
			// LogRecord logRecord = new LogRecord();
			// logRecord.bulifLogParams(param);
			// if(PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSearchUpdateClassIds()))
			// {
			// String[]
			// classIds=trainingClassQueryCommond.getSearchUpdateClassIds();
			// for(String classId:classIds){
			// LogRecordParam paramChild = new LogRecordParam();
			// paramChild.setOpdataId(classId);//操作主数据id
			// if
			// (PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSubmintType())
			// &&
			// TrainingConstants.IS_REPORT_Y.equals(trainingClassQueryCommond.getSubmintType()))
			// {
			// //提交审核
			// paramChild.setOpbefoData("培训班ID=====>" + classId +
			// "\n提交审核状态====>未提交");//操作前数据
			// paramChild.setOpafteData("培训班ID=====>" + classId +
			// "\n提交审核状态====>已提交");//操作后数据
			// paramChild.setOpmodule("高校功能 - 院校维护培训班 - 提交审核");
			// paramChild.setOpcontent("提交审核培训班");
			// }else if
			// (PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSubmintType())
			// &&
			// TrainingConstants.IS_AUDIT_CLASS_Y.equals(trainingClassQueryCommond.getSubmintType()))
			// {
			// //审核通过
			// paramChild.setOpbefoData("培训班ID=====>" + classId +
			// "\n审核状态====>未审核或审核未通过");//操作前数据
			// paramChild.setOpafteData("培训班ID=====>" + classId +
			// "\n审核状态====>审核通过");//操作后数据
			// paramChild.setOpmodule("工委 - 工委完善培训班 - 审核通过");
			// paramChild.setOpcontent("培训班审核通过");
			// }else if
			// (PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSubmintType())
			// &&
			// TrainingConstants.IS_AUDIT_CLASS_N.equals(trainingClassQueryCommond.getSubmintType()))
			// {
			// //审核未通过
			// paramChild.setOpbefoData("培训班ID=====>" + classId +
			// "\n审核状态====>未审核或审核通过");//操作前数据
			// paramChild.setOpafteData("培训班ID=====>" + classId +
			// "\n审核状态====>审核未通过");//操作后数据
			// paramChild.setOpmodule("工委 - 工委完善培训班 - 审核驳回");
			// paramChild.setOpcontent("培训班审核未通过");
			// }else if
			// (PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSubmintType())
			// &&
			// TrainingConstants.IS_PUBLISH_N_TO_Y.equals(trainingClassQueryCommond.getSubmintType()))
			// {
			// //发布
			// paramChild.setOpbefoData("培训班ID=====>" + classId +
			// "\n发布状态====>未发布");//操作前数据
			// paramChild.setOpafteData("培训班ID=====>" + classId +
			// "\n发布状态====>已发布");//操作后数据
			// paramChild.setOpmodule("工委 - 工委完善培训班 - 发布");
			// paramChild.setOpcontent("发布培训班");
			// }else if
			// (PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSubmintType())
			// &&
			// TrainingConstants.IS_PUBLISH_Y_TO_N.equals(trainingClassQueryCommond.getSubmintType()))
			// {
			// //未发布
			// paramChild.setOpbefoData("培训班ID=====>" + classId +
			// "\n发布状态====>已发布");//操作前数据
			// paramChild.setOpafteData("培训班ID=====>" + classId +
			// "\n发布状态====>未发布");//操作后数据
			// paramChild.setOpmodule("工委 - 工委完善培训班 - 撤销发布");
			// paramChild.setOpcontent("撤销发布培训班");
			// }else if
			// (PropertyUtil.objectNotEmpty(trainingClassQueryCommond.getSubmintType())
			// &&
			// TrainingConstants.IS_ACTIVE_Y_TO_N.equals(trainingClassQueryCommond.getSubmintType()))
			// {
			// //删除班级
			// paramChild.setOpbefoData("培训班ID=====>" + classId +
			// "\n活动状态====>启用");//操作前数据
			// paramChild.setOpafteData("培训班ID=====>" + classId +
			// "\n活动状态====>作废");//操作后数据
			// paramChild.setOpmodule("高校功能 - 院校维护培训班 - 删除");
			// paramChild.setOpcontent("删除培训班");
			// }
			// paramChild.setOptype(UniteConstants.UPDATE);
			// logRecord.bulifLogParams(paramChild);
			// paramList.add(paramChild);
			// }
			// param.setRecordlist(paramList);
			// try {
			// LogThread logThread = new LogThread(param);
			// Thread thread = new Thread(logThread);
			// thread.start();
			// } catch (Exception e) {
			// // TODO: handle exception
			// e.printStackTrace();
			// }
			// }
		}
	}

	/**
	 * 根据查询条件获取专题班信息
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-11
	 */
	@SuppressWarnings("unused")
	private boolean findSameClassName(String classId, String className) throws Exception {
		TrainingClassQueryCommond queryCommond = new TrainingClassQueryCommond();
		List<TrainingClass> list = (List<TrainingClass>) this.findAllList(queryCommond);
		return false;
	}

	/**
	 * 在添加和修改的时候判断培训班名称是否一样
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-17
	 */
	@Override
	public boolean decideClassName(TrainingClassValidCommond commond) throws Exception {
		return this.trainingClassDao.decideClassName(commond);
	}

	/**
	 * 班级信息值的传递
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-18
	 */
	@Override
	public TrainingClassValidCommond swapClassInfo(TrainingClassValidCommond vcommond) throws Exception {
		TrainingClass trainingClass = (TrainingClass) vcommond.toEntity();

		if (PropertyUtil.objectNotEmpty(trainingClass.getClassType())) {
			vcommond.setClassType(trainingClass.getClassType().getDataCode());// 班级类型
		}

		if (PropertyUtil.objectNotEmpty(trainingClass.getClassnamePeriod())) {
			vcommond.setClassnamePeriod(trainingClass.getClassnamePeriod().getDataCode());// 期数
		}

		if (PropertyUtil.objectNotEmpty(trainingClass.getBeginDate())) {
			// 开班时间
			vcommond.setBeginDateStr(DateUtil.getDateString(trainingClass.getBeginDate(), "yyyy-MM-dd"));
		}

		if (PropertyUtil.objectNotEmpty(trainingClass.getEndDate())) {
			// 结班时间
			vcommond.setEndDateStr(DateUtil.getDateString(trainingClass.getEndDate(), "yyyy-MM-dd"));
		}

		if (PropertyUtil.objectNotEmpty(trainingClass.getEnterBeginTime())) {
			// 报名开始时间
			vcommond.setEnterBeginTimeStr(DateUtil.getDateString(trainingClass.getEnterBeginTime(), "yyyy-MM-dd"));
		}

		if (PropertyUtil.objectNotEmpty(trainingClass.getEnterEndTime())) {
			// 报名结束时间
			vcommond.setEnterEndTimeStr(DateUtil.getDateString(trainingClass.getEnterEndTime(), "yyyy-MM-dd"));
		}

		ClassUserQueryCommond qCommond = new ClassUserQueryCommond();
		if (PropertyUtil.objectNotEmpty(vcommond.getClassId()))
			qCommond.setSearchClassID(vcommond.getClassId());
		// 判断是否是单位权限
		if (PropertyUtil.objectNotEmpty(vcommond.getManagerDepartId()) && vcommond.getDeptCode().equals("department_admin"))
			qCommond.setSearchDepId(vcommond.getManagerDepartId());

		// 报名人数
		qCommond.setAttendanceState(null);
		vcommond.setReportedNum(classUserDao.findClassUserNumByAttendanceState(qCommond));
		// 全勤人数
		qCommond.setAttendanceState(1);
		vcommond.setAttendanceNum(classUserDao.findClassUserNumByAttendanceState(qCommond));
		// 缺勤人数
		qCommond.setAttendanceState(2);
		vcommond.setAbsenceNum(classUserDao.findClassUserNumByAttendanceState(qCommond));
		// 请假人数
		qCommond.setAttendanceState(3);
		vcommond.setLeaveNum(classUserDao.findClassUserNumByAttendanceState(qCommond));
		// 未出勤人数
		qCommond.setAttendanceState(4);
		vcommond.setNoAttendanceNum(classUserDao.findClassUserNumByAttendanceState(qCommond));
		// 出勤率
		if (vcommond.getReportedNum() <= 0)
			vcommond.setAttendanceRate("0.00%");
		else {
			vcommond.setAttendanceRate((new BigDecimal((vcommond.getAttendanceNum().doubleValue() / vcommond.getReportedNum().doubleValue() * 100)).setScale(2, BigDecimal.ROUND_HALF_UP)).toString()
					+ "%");
		}
		return vcommond;
	}

	/**
	 * 拼凑班级名称
	 * 
	 * @param commond
	 * @return
	 * @author Max
	 */
	private String spellClassName(TrainingClassValidCommond vCommond) {
		String classMainName = "";
		classMainName = vCommond.getClassnameYear() + "年" + vCommond.getClassName();
		vCommond.setClassMainName(classMainName);
		return classMainName;
	}

	public Date addDay(String date, int days) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cd = Calendar.getInstance();
		cd.setTime(sdf.parse(date));
		cd.add(Calendar.DATE, days);// 增加一天
		return cd.getTime();
	}

	/**
	 * 更新培训班信息
	 * 
	 * @param commond
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-19
	 */
	@Override
	public String updateTraingClass(TrainingClassValidCommond commond) throws Exception {
		TrainingClass trainClass = trainingClassDao.find(TrainingClass.class, commond.getClassId());
		trainClass.setSignupOr(commond.getSignupOr());
		// 更新前班级信息 by NingSS at 20150504
		// String preTrainClass=trainClass.toString();
		TrainingClass commClass = (TrainingClass) commond.toEntity();
		if (this.trainingClassDao.decideClassName(commond)) {
			return "hava";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 部委完善信息时：比较一下更新后数据与更新前数据，总结出更新了哪些字段信息（共8个信息）
		if (PropertyUtil.objectNotEmpty(commond.getRoleCode()) && RoleConstants.ROLE_CODE_BW_ADMIN.equals(commond.getRoleCode())) {
			StringBuffer updateInformation = new StringBuffer();
			// 部委完善班级信息8个字段的情况：1、字段更新前有值 2、字段更新前没有值
			if (PropertyUtil.objectNotEmpty(trainClass.getBeginDate())) {// 有值
				String beginDateS = sdf.format(trainClass.getBeginDate());
				if (PropertyUtil.objectNotEmpty(commond.getBeginDateStr()) && !beginDateS.equals(commond.getBeginDateStr())) {
					updateInformation.append("开班时间、");
				}
			} else {// 没有值
				updateInformation.append("开班时间、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getEndDate())) {// 有值
				String endDateS = sdf.format(trainClass.getEndDate());
				if (PropertyUtil.objectNotEmpty(commond.getEndDateStr()) && !endDateS.equals(commond.getEndDateStr())) {
					updateInformation.append("结业时间、");
				}
			} else {// 没有值
				updateInformation.append("结业时间、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getEnterBeginTime())) {// 有值
				String enterBeginTimeS = sdf.format(trainClass.getEnterBeginTime());
				if (PropertyUtil.objectNotEmpty(commond.getEnterBeginTimeStr()) && !enterBeginTimeS.equals(commond.getEnterBeginTimeStr())) {
					updateInformation.append("报名开始时间、");
				}
			} else {// 没有值
				updateInformation.append("报名开始时间、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getEnterEndTime())) {// 有值
				String enterEndTimeS = sdf.format(trainClass.getEnterEndTime());
				if (PropertyUtil.objectNotEmpty(commond.getEnterEndTimeStr()) && !enterEndTimeS.equals(commond.getEnterEndTimeStr())) {
					updateInformation.append("报名截止时间、");
				}
			} else {// 没有值
				updateInformation.append("报名截止时间、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getTrainingDeptId())||PropertyUtil.objectNotEmpty(trainClass.getTrainingDeptName())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getTrainingDeptId()) && !trainClass.getTrainingDeptId().equals(commond.getTrainingDeptId())||PropertyUtil.objectNotEmpty(commond.getTrainingDeptName()) && !trainClass.getTrainingDeptName().equals(commond.getTrainingDeptName())) {
					updateInformation.append("培训地点、");
				}
			} else {// 没有值
				if (PropertyUtil.objectNotEmpty(commond.getTrainingDeptId())||PropertyUtil.objectNotEmpty(trainClass.getTrainingDeptName())) {
					updateInformation.append("培训地点、");
				}
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getTrainingAddress())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getTrainingAddress()) && !trainClass.getTrainingAddress().equals(commond.getTrainingAddress())) {
					updateInformation.append("培训地点、");
				}
			} else {// 没有值
				if (PropertyUtil.objectNotEmpty(commond.getTrainingAddress())) {
					updateInformation.append("培训地点、");
				}
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getTrainingHour())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getTrainingHour()) && !trainClass.getTrainingHour().equals(commond.getTrainingHour())) {
					updateInformation.append("学时、");
				}
			} else {// 没有值
				if (PropertyUtil.objectNotEmpty(commond.getTrainingHour())) {
					updateInformation.append("学时、");
				}
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getContactPeople())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getContactPeople()) && !trainClass.getContactPeople().equals(commond.getContactPeople())) {
					updateInformation.append("联系人、");
				}
			} else {// 没有值
				updateInformation.append("联系人、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getContactTel())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getContactTel()) && !trainClass.getContactTel().equals(commond.getContactTel())) {
					updateInformation.append("联系电话、");
				}
			} else {// 没有值
				updateInformation.append("联系电话、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getFax())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getFax()) && !trainClass.getFax().equals(commond.getFax())) {
					updateInformation.append("传真、");
				}
			} else {// 没有值
				updateInformation.append("传真、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getBeoffStation())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getBeoffStation()) && !trainClass.getBeoffStation().equals(commond.getBeoffStation())) {
					updateInformation.append("离岗状态、");
				}
			} else {// 没有值
				updateInformation.append("离岗状态、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getCategoryId())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getCategoryId()) && !trainClass.getCategoryId().equals(commond.getCategoryId())) {
					updateInformation.append("培训类别、");
				}
			} else {// 没有值
				updateInformation.append("培训类别、");
			}
			if (PropertyUtil.objectNotEmpty(trainClass.getClassnameYear())) {// 有值
				if (PropertyUtil.objectNotEmpty(commond.getClassnameYear()) && !trainClass.getClassnameYear().equals(commond.getClassnameYear())) {
					updateInformation.append("年度、");
				}
			} else {// 没有值
				updateInformation.append("年度、");
			}
			if (PropertyUtil.objectNotEmpty(updateInformation.toString())) {
				commond.setUpdateInformation(updateInformation.deleteCharAt(updateInformation.length() - 1).toString());
			}
			// commond.setUpdateInformation(updateInformation.toString().substring(0,updateInformation.toString().length()-1));
		}
		// 以下是正常更新班级信息的流程
		if (PropertyUtil.objectNotEmpty(commond.getBeginDateStr())) {
			String beginDateStr = commond.getBeginDateStr();
			trainClass.setBeginDate(sdf.parse(beginDateStr));
		}
		if (PropertyUtil.objectNotEmpty(commond.getEndDateStr())) {
			String endDateStr = commond.getEndDateStr();
			trainClass.setEndDate(sdf.parse(endDateStr));
			// 更改结班时间同时更新评估开始结束时间为结班时间的前1天后2天 add by LongJZ at 2016-3-30
			commond.setAssessStartTime(addDay(endDateStr, -1));
			commond.setAssessEndTime(addDay(endDateStr, 2));
		}
		if (PropertyUtil.objectNotEmpty(commond.getEnterBeginTimeStr())) {
			String enterBeginTimeStr = commond.getEnterBeginTimeStr();
			trainClass.setEnterBeginTime(sdf.parse(enterBeginTimeStr));
		}
		if (PropertyUtil.objectNotEmpty(commond.getEnterEndTimeStr())) {
			String enterEndTimeStr = commond.getEnterEndTimeStr();
			trainClass.setEnterEndTime(sdf.parse(enterEndTimeStr));
		}

		if (PropertyUtil.objectNotEmpty(commond.getTrainingClass().getSignUpState())) {
			trainClass.setSignUpState(commond.getTrainingClass().getSignUpState());
		}
		trainClass.setClassName(commClass.getClassName());
		// trainClass.setMinistrieID(commClass.getMinistrieID());
		// trainClass.setMinistrieName(commClass.getMinistrieName());

		Map<String, BaseData> baseDataMap = baseDataCacheUtil.getBaseData();
		// BaseData bd=baseDataMap.get(parameter[0]);
		if (PropertyUtil.objectNotEmpty(commClass.getClassType())) {
			trainClass.setClassType(commClass.getClassType());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getClassName())) {
			trainClass.setClassName(commClass.getClassName());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getTrainingAddress())) {
			trainClass.setTrainingAddress(commClass.getTrainingAddress());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getTrainingDeptId())) {
			trainClass.setTrainingDeptId(commClass.getTrainingDeptId());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getTrainingDeptName())) {
			trainClass.setTrainingDeptName(commClass.getTrainingDeptName());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getFax())) {
			trainClass.setFax(commClass.getFax());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getContactPeople())) {
			trainClass.setContactPeople(commClass.getContactPeople());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getContactTel())) {
			trainClass.setContactTel(commClass.getContactTel());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getClassDescription())) {
			trainClass.setClassDescription(commClass.getClassDescription());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getPhone())) {
			trainClass.setPhone(commClass.getPhone());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getClassnameYear())) {
			trainClass.setClassnameYear(commClass.getClassnameYear());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getBeoffStation())) {
			trainClass.setBeoffStation(commClass.getBeoffStation());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getCategoryId())) {
			trainClass.setCategoryId(commClass.getCategoryId());
		}
		if (PropertyUtil.objectNotEmpty(commClass.getTrainingHour())) {
			trainClass.setTrainingHour(commClass.getTrainingHour());
		}
		// 删除承办部委&指定报名机构
		trainingClassDao.deleteCBZD(commond);

		// 属性拷贝
		// PropertyUtil.propertyDynamicUpdate(trainClass,commClass);

		// 指定报名机构
		ClassSignUpDepartment csp;
		if (PropertyUtil.objectNotEmpty(commond.getSignUpDepartmentIds()) && PropertyUtil.objectNotEmpty(commond.getSignUpDepartmentIds()[0])) {
			String[] ids = commond.getSignUpDepartmentIds()[0].split(",");
			for (String i : ids) {
				csp = new ClassSignUpDepartment();
				csp.setActiveState(ClassSignUpDepartment.IS_ACTIVE_Y);
				csp.setCreateDate(new Date());
				Department d = new Department();
				d.setDeptID(i);
				csp.setDept(d);
				csp.setTrainingClass(trainClass);
				saveEntity(csp);
				commond.getTrainingClass().getSignUpDepartment().add(csp);
			}
		} else {
			csp = new ClassSignUpDepartment();
			csp.setActiveState(ClassSignUpDepartment.IS_ACTIVE_Y);
			csp.setCreateDate(new Date());
			Department d = new Department();
			d.setDeptID(commond.getCurrenDepartmentId());
			csp.setDept(d);
			csp.setTrainingClass(trainClass);
			saveEntity(csp);
			commond.getTrainingClass().getSignUpDepartment().add(csp);
		}
		// 指定管理范围
		ClassScopeDepartment cspd;
		if (PropertyUtil.objectNotEmpty(commond.getScopeDepartmentIds()) && PropertyUtil.objectNotEmpty(commond.getScopeDepartmentIds()[0])) {
			String[] ids = commond.getScopeDepartmentIds()[0].split(",");
			for (String i : ids) {
				cspd = new ClassScopeDepartment();
				cspd.setActiveState(ClassScopeDepartment.IS_ACTIVE_Y);
				cspd.setCreateDate(new Date());
				Department d = new Department();
				d.setDeptID(i);
				cspd.setDept(d);
				cspd.setTrainingClass(trainClass);
				saveEntity(cspd);
				trainClass.getScopeDepartment().add(cspd);
			}
		} else {
			cspd = new ClassScopeDepartment();
			cspd.setActiveState(ClassSignUpDepartment.IS_ACTIVE_Y);
			cspd.setCreateDate(new Date());
			Department d = new Department();
			d.setDeptID(commond.getCurrenDepartmentId());
			cspd.setDept(d);
			cspd.setTrainingClass(trainClass);
			saveEntity(cspd);
			trainClass.getScopeDepartment().add(cspd);
		}

		// BeanUtils.copyProperties(commClass, trainClass, new
		// String[]{"scopeDepartment","signUpDepartment"});
		trainClass.setSignUpDepartment(commClass.getSignUpDepartment());
		trainClass.setScopeDepartment(commClass.getScopeDepartment());
		// //配置数据字典
		// trainClass=configureBaseDataForUpdate(trainClass,commond);
		// //拼凑名称
		// String classMainName=spellClassName(commond);
		// trainClass.setClassMainName(classMainName);
		// if (PropertyUtil.objectNotEmpty(commond.getBeginDateStr())) {
		// trainClass.setBeginDate(DateUtil.getDateByString(commond.getBeginDateStr(),
		// "yyyy-MM-dd"));
		// }
		// if (PropertyUtil.objectNotEmpty(commond.getEndDateStr())) {
		// trainClass.setEndDate(DateUtil.getDateByString(commond.getEndDateStr(),
		// "yyyy-MM-dd"));
		// }
		// if (PropertyUtil.objectNotEmpty(commond.getEnterBeginTimeStr())) {
		// trainClass.setEnterBeginTime(DateUtil.getDateByString(commond.getEnterBeginTimeStr(),
		// "yyyy-MM-dd"));
		// }
		// if (PropertyUtil.objectNotEmpty(commond.getEnterEndTimeStr())) {
		// trainClass.setEnterEndTime(DateUtil.getDateByString(commond.getEnterEndTimeStr(),
		// "yyyy-MM-dd"));
		// }
		// if(!PropertyUtil.objectNotEmpty(commond.getClassDescription())) {
		// trainClass.setClassDescription(null);
		// }
		// //开班结班状态判断
		trainClass = decideOpenState(commond, trainClass);
		// 如果状态是审核驳回修改以后，审核状态变成未审核，提交状态变成未提交
		/*
		 * if(trainClass.getAuditState().equals(TrainingClass.IS_AUDIT_N)) {
		 * trainClass.setAuditState(TrainingClass.IS_N_AUDIT);
		 * trainClass.setAuditDate(null);
		 * trainClass.setReportState(TrainingClass.IS_REPORT_N);
		 * trainClass.setReportDate(null); }
		 */
		trainClass.setPerfectState(TrainingClass.PERFECTSTATE_Y);// 已完善
		trainClass.setLatestOperateDate(new Date());
		trainClass.setLastOperateTime(new Date());
		this.getDaoSupport().update(trainClass);

		// //添加记录日志的逻辑 add by NingSS at 20150504
		// LogRecord logRecord = new LogRecord();
		// LogRecordParam paramChild = new LogRecordParam();
		// paramChild.setOpdataId(trainClass.getClassId());//操作主数据id
		// paramChild.setOpbefoData(preTrainClass);//操作前数据
		// paramChild.setOpafteData(trainClass.toString());//操作后数据
		// paramChild.setOpmodule("高校功能 - 院校维护培训班 - 更新");//操作模块
		// paramChild.setOpcontent("更新培训班");//操作说明
		// paramChild.setOptype(UniteConstants.UPDATE); //操作类型
		// logRecord.bulifLogParams(paramChild);
		// try {
		// LogThread logThread = new LogThread(paramChild);
		// Thread thread = new Thread(logThread);
		// thread.start();
		// } catch (Exception e) {
		// // TODO: handle exception
		// e.printStackTrace();
		// }
		return "";
	}

	public TrainingClass decideOpenState(TrainingClassValidCommond commond, TrainingClass trainClass) throws Exception {
		/*
		 * 添加班级状态和报名状态的判断: 1、只要是未发布的班级状态就是未开班 2、只要是未发布的报名状态就是未开始报名
		 * 3、已发布且已开班的报名状态就是报名结束
		 */
		if (PropertyUtil.objectNotEmpty(trainClass.getPublishState()) && (TrainingClass.IS_PUBLISH_N == trainClass.getPublishState())) {// 未发布
			// 未开班
			trainClass.setOpenState(TrainingClass.IS_OPENSTATE_N);
			// 报名未开始
			trainClass.setSignUpState(TrainingClass.IS_SIGNUP_N);

		} else {// 已发布
				// 原有逻辑
				// 根据开班时间判断开班状态 by Max at 2013-12-17
			if (trainClass.getBeginDate() != null && trainClass.getEndDate() != null) {
				Date beginDate = trainClass.getBeginDate();
				Date endDate = trainClass.getEndDate();
				endDate=DateUtil.changeDate23H59m59s999ms(endDate);
				Date nowDate = new Date();
				nowDate=DateUtil.changeDate23H59m59s999ms(nowDate);
				java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
				java.util.Calendar c1 = java.util.Calendar.getInstance();
				java.util.Calendar c2 = java.util.Calendar.getInstance();
				java.util.Calendar c3 = java.util.Calendar.getInstance();
				c1.setTime(df.parse(df.format(beginDate)));
				c2.setTime(df.parse(df.format(endDate)));
				c3.setTime(df.parse(df.format(nowDate)));
				int result1 = c1.compareTo(c3);
				int result2 = c2.compareTo(c3);
				if (result1 == 0) {
					// 开班
					trainClass.setOpenState(TrainingClass.IS_OPENSTATE_Y);
					// trainClass.setEndState(TrainingClass.IS_ENDSTATE_N);

				} else if (result1 < 0) {
					if (result2 < 0) {
						// 结班
						trainClass.setOpenState(TrainingClass.IS_ENDSTATE_Y);
						// trainClass.setEndState(TrainingClass.IS_ENDSTATE_Y);
					} else {
						// 开班
						trainClass.setOpenState(TrainingClass.IS_OPENSTATE_Y);
						// trainClass.setEndState(TrainingClass.IS_ENDSTATE_N);
					}
				} else {
					// 未开班
					trainClass.setOpenState(TrainingClass.IS_OPENSTATE_N);
					// trainClass.setEndState(TrainingClass.IS_ENDSTATE_N);
				}
			}

			// 新添逻辑：已发布且已开班的报名状态就是报名结束
			if (PropertyUtil.objectNotEmpty(trainClass.getOpenState()) && (TrainingClass.IS_OPENSTATE_Y == trainClass.getOpenState())) {
				// 报名结束
				trainClass.setSignUpState(TrainingClass.IS_SIGNUP_END);
			} else {
				// 根据报名时间判断报名状态
				// 报名结束
				if (PropertyUtil.objectNotEmpty(trainClass.getEnterEndTime()) && compare_date(trainClass.getEnterEndTime()) <= 0)
					trainClass.setSignUpState(TrainingClass.IS_SIGNUP_END);
				// 正在报名
				else if (PropertyUtil.objectNotEmpty(trainClass.getEnterBeginTime()) && compare_date(trainClass.getEnterBeginTime()) <= 0)
					trainClass.setSignUpState(TrainingClass.IS_SIGNUP_BEGIN);
				// 报名未开始
				else if (PropertyUtil.objectNotEmpty(trainClass.getEnterBeginTime()) && compare_date(trainClass.getEnterBeginTime()) > 0)
					trainClass.setSignUpState(TrainingClass.IS_SIGNUP_N);
				else
					trainClass.setSignUpState(trainClass.getSignUpState());
			}
		}
		return trainClass;
	}

	/**
	 * 配置数据字典的数据
	 * 
	 * @param tclass
	 * @return
	 * @author Max
	 * @throws Exception
	 * @date 2013-12-13
	 */
	private TrainingClass configureBaseDataForUpdate(TrainingClass tclass, TrainingClassValidCommond vCommond) throws Exception {
		Map<String, BaseData> baseDataMap = baseDataCacheUtil.getBaseData();

		if (PropertyUtil.objectNotEmpty(vCommond.getClassType())) {
			BaseData data = new BaseData();
			data.setDataCode(vCommond.getClassType());
			BaseData b = baseDataMap.get(vCommond.getClassType());
			data.setDataID(b.getDataID());
			tclass.setClassType(data);
		}
		if (PropertyUtil.objectNotEmpty(vCommond.getApplyWay())) {
			BaseData data = new BaseData();
			data.setDataCode(vCommond.getApplyWay());
			BaseData b = baseDataMap.get(vCommond.getApplyWay());
			data.setDataID(b.getDataID());
			tclass.setApplyWay(data);
		}
		if (PropertyUtil.objectNotEmpty(vCommond.getClassnamePeriod())) {
			BaseData data = new BaseData();
			data.setDataCode(vCommond.getClassnamePeriod());
			BaseData b = baseDataMap.get(vCommond.getClassnamePeriod());
			data.setDataID(b.getDataID());
			tclass.setClassnamePeriod(data);
		}
		return tclass;
	}

	/**
	 * 根据查询条件获取专题班信息(区级项目报名列表)
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2013-12-25
	 */
	@Override
	public List<TrainingClassQueryBean> findOrganizationTrainingClassList(TrainingClassQueryCommond commond) throws Exception {
		List<TrainingClassQueryBean> findList = this.trainingClassDao.findOrganizationTrainingClassList(commond);
		for (TrainingClassQueryBean tcqb : findList) {
			// if(!PropertyUtil.objectNotEmpty(tcqb.getDeptName())){
			// tcqb.setDeptName(commond.getSearchDepName());
			// }
		}
		return findList;
	}

	/**
	 * 更改专题班开班状态 （调度使用）
	 * 
	 * @param commond
	 * @return
	 * @author Max
	 * @date 2013-12-25
	 */
	@Override
	public String updateThematicClassOpenStateQuartz(TrainingClassQueryCommond commond) throws Exception {

		// ThematicClassValidCommond thematicClassValidCommond = new
		// ThematicClassValidCommond();
		// thematicClassValidCommond.setSearchNowTime(new Date());
		// // 未开班
		// thematicClassValidCommond.setOpenState(ThematicClass.IS_OPENSTATE_N);
		// thematicClassDao.updateThematicClassPart(thematicClassValidCommond);
		// // 已开班
		// thematicClassValidCommond.setOpenState(ThematicClass.IS_OPENSTATE_Y);
		// thematicClassDao.updateThematicClassPart(thematicClassValidCommond);
		// // 已结班
		// thematicClassValidCommond.setOpenState(ThematicClass.IS_OPENSTATE_YN);
		// thematicClassDao.updateThematicClassPart(thematicClassValidCommond);

		commond.setSearchNowDate("yes");
		commond.setSearchEndState(TrainingClass.IS_ENDSTATE_N);
		commond.setSearchActiveState(TrainingClass.IS_ACTIVE_Y);
		// 查询为结班和结班时间<当前时间的所有班级
		List<TrainingClassQueryBean> list = trainingClassDao.findTrainingClassList2(commond);
		if (list != null && list.size() > 0) {
			// 拼写数据
			TrainingClassPartFieldUpdateBean trainingClassPartFieldUpdateBean = new TrainingClassPartFieldUpdateBean();
			TrainingClassValidCommond trainingClassValidCommond = new TrainingClassValidCommond();
			trainingClassPartFieldUpdateBean.setiQueryCommond(commond);
			trainingClassValidCommond.setEndState(TrainingClass.IS_ENDSTATE_Y);
			trainingClassValidCommond.setLatestOperateDate(new Date());
			trainingClassPartFieldUpdateBean.setiCommond(trainingClassValidCommond);

			for (int i = 0; i < list.size(); i++) {
				TrainingClassQueryBean bean = list.get(i);
				TrainingClassQueryCommond trainingClassQueryCommond = (TrainingClassQueryCommond) trainingClassPartFieldUpdateBean.getiQueryCommond();
				trainingClassQueryCommond.setSearchUpdateClassIds(new String[] { bean.getClassId() });
				// 执行底层更新结班状态
				this.updateTrainingClassState(trainingClassPartFieldUpdateBean);
				// 市级班的不去更新班级学员的学时
			}
		}
		return "";
	}

	/**
	 * 查单位上报区级项目审核
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2013-12-30
	 */
	public List<TrainingClassQueryBean> findTrainingClassListForAuditUnitPorject(TrainingClassQueryCommond queryCommond) throws Exception {
		// 更改为根据treePath查询，包含子单位 By HuangTF At 2014-06-17
		// 查询单位路径
		if (PropertyUtil.objectNotEmpty(queryCommond.getSearchOrganizerId())) {
			ClassUserQueryCommond classUserQueryCommond = new ClassUserQueryCommond();
			classUserQueryCommond.setSearchDepId(queryCommond.getSearchOrganizerId().trim());
			queryCommond.setTreePath(classUserDao.findDepTreePath(classUserQueryCommond).get(0).getTreepath());
		}
		return this.trainingClassDao.findTrainingClassListForUnitProject(queryCommond);
	}

	/**
	 * 查询单位上报市级项目审核
	 * 
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @date 2014-1-7
	 */
	public List<TrainingClassQueryBean> findTrainingClassListForAuditDS(TrainingClassQueryCommond queryCommond) throws Exception {
		// 查询单位路径
		if (PropertyUtil.objectNotEmpty(queryCommond.getSearchOrganizerId())) {
			ClassUserQueryCommond classUserQueryCommond = new ClassUserQueryCommond();
			classUserQueryCommond.setSearchDepId(queryCommond.getSearchOrganizerId());
			queryCommond.setTreePath(classUserDao.findDepTreePath(classUserQueryCommond).get(0).getTreepath());
		}
		return this.trainingClassDao.findTrainingClassListForAuditDS(queryCommond);
	}

	/**
	 * 向干教网同步数据查询培训项目列表
	 * 
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @date 2014-1-9
	 */
	public List<SyncTrainingClassQueryBean> findTrainingClassListSyncToGJW(TrainingClassQueryCommond queryCommond) throws Exception {
		// 查询单位路径
		if (PropertyUtil.objectNotEmpty(queryCommond.getSearchOrganizerId())) {
			ClassUserQueryCommond classUserQueryCommond = new ClassUserQueryCommond();
			classUserQueryCommond.setSearchDepId(queryCommond.getSearchOrganizerId());
			queryCommond.setTreePath(classUserDao.findDepTreePath(classUserQueryCommond).get(0).getTreepath());
		}
		return this.trainingClassDao.findTrainingClassListSyncToGJW(queryCommond);
	}

	/**
	 * 更新班级表项目审核时间
	 * 
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-1-17
	 */
	public void updateAduitDate(String classId, String aduitDate) throws Exception {
		this.trainingClassDao.updateAduitDate(classId, aduitDate);
	}

	/**
	 * 根据用户id查询用户部门id
	 * 
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2014-4-12
	 */
	@Override
	public String getDepIdByUserId(String userId) throws Exception {
		DepartmentUserBean dep = this.trainingClassDao.getDepIdByUserId(new String[] { userId }).get(0);
		return dep.getDepId();
	}

	public List<DepartmentUserBean> getDepIdByUserIds(String[] userId) throws Exception {
		return this.trainingClassDao.getDepIdByUserId(userId);
	}

	/**
	 * 导入干部库历史培训信息
	 * 
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Max
	 * @throws Exception
	 * @date 2014-5-9
	 */
	@Override
	public String importHisTrainingInfo(byte[] bs) throws Exception {
		InputStream in = null;
		ExcelSheet sheet = null;
		String msg = "";
		in = new ByteArrayInputStream(bs);
		// 读取excel
		sheet = excelUtils.readFile(in);
		if (sheet != null) {
			Map<String, String> userIDs = new HashMap<String, String>();
			userIDs = trainingClassDao.getUserIDInfo();

			// 读取行
			List<ExcelRow> rowList = sheet.getRowList();
			// 第一行是标题，从第二行开始读取
			for (int i = 1; i < rowList.size(); i++) {
				List<String> notDoUserIDs = new ArrayList<String>();// 由于信息不全造成未执行添加的人员ID
				TrainingClass trainingClass = new TrainingClass();// 班级对象
				List<String> doUserIDs = new ArrayList<String>();// 执行添加的人员ID
				ExcelRow row = rowList.get(i);
				try {
					List<ExcelCell> cellList = row.getCellList();
					ExcelCell excelCell = null;
					// 前五列 表示的是班级信息
					for (int f = 0; f < 5; f++) {
						excelCell = cellList.get(f);
						if (excelCell.getCellValue() != null) {
							if (f == 0) {
								trainingClass.setClassnameYear(excelCell.getCellValue().toString());// 年度
							} else if (f == 1) {
								trainingClass.setClassName(excelCell.getCellValue().toString());// 班级名称
							} else if (f == 2) {
								SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
								Date date = format.parse(excelCell.getCellValue().toString());
								trainingClass.setBeginDate(date);// 开班时间
								// 报名开始时间 报名结束时间 取开班时间的前一天
								Calendar calendar = Calendar.getInstance();
								calendar.setTime(date);
								calendar.add(Calendar.DAY_OF_MONTH, -1);
								Date date1 = calendar.getTime();
								trainingClass.setEnterBeginTime(date1);// 报名开始时间
								trainingClass.setEnterEndTime(date1);// 报名结束时间
							} else if (f == 3) {
								SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
								Date date = format.parse(excelCell.getCellValue().toString());
								trainingClass.setEndDate(date);// 结班时间
							} else if (f == 4) {
								trainingClass.setTrainingHour(Double.parseDouble(excelCell.getCellValue().toString()));
							}
						} else {
							// 前5列如果有空 表示有错
							msg = "第" + row.getRowNum() + "行记录导入出错！" + "错误原因：第" + excelCell.getCellNum() + "列出现空数据";
							return msg;
						}
					}
					// 拼凑班级信息
					trainingClass = buildTrainingClass(trainingClass);
					// 后面的就是 人员信息
					for (int a = 5; a < cellList.size(); a = a + 2) {
						excelCell = cellList.get(a);
						if (excelCell.getCellValue() != null) {
							String key = "";
							if (excelCell.getCellNum() % 2 == 0) {
								key = excelCell.getCellValue().toString().replace(" ", "");// 姓名
							}
							excelCell = cellList.get(a + 1);

							key = key + "+" + excelCell.getCellValue().toString();// 姓名+出生年月
							// 通过姓名+出生年月在Map集合中找到这个人的userID
							String userId = userIDs.get(key);
							if (userId != null) {
								// 人员ID不为空的可以执行添加操作
								doUserIDs.add(userId);
							} else {
								// 未执行添加的人员
								notDoUserIDs.add(key);
							}
						} else {
							msg = "第" + row.getRowNum() + "行记录导入出错！" + "错误原因：第" + excelCell.getCellNum() + "列出现空数据";
							return msg;
						}
					}
					// 执行添加班级和人员的操作
					// this.addTraingInfoByExcel(trainingClass, doUserIDs);

				} catch (Exception e) {
					msg = "第" + row.getRowNum() + "行记录导入出错！" + "错误原因：" + e.getMessage();
				}

				// 输出未添加的人员
				if (notDoUserIDs.size() > 0) {
					StringBuffer buffer = new StringBuffer();
					for (int d = 0; d < notDoUserIDs.size(); d++) {
						if (notDoUserIDs.get(d).toString() != null && !("+").equals(notDoUserIDs.get(d).toString())) {
							buffer.append(notDoUserIDs.get(d).toString() + ",");
						}
					}
				}
			}
		}

		if (in != null && !"".equals(in)) {
			in.close();
		}
		return msg;
	}

	/**
	 * 导入干部库历史在线培训信息
	 * 
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Max
	 * @throws Exception
	 * @date 2014-5-9
	 */
	@Override
	public String importHisOnLineTrainingInfo(byte[] bs) throws Exception {
		InputStream in = null;
		ExcelSheet sheet = null;
		String msg = "";
		in = new ByteArrayInputStream(bs);
		List<String> notDoUserIDs = new ArrayList<String>();// 由于信息不全造成未执行添加的人员ID
		List<UserIdAndYear> doUserIDs = new ArrayList<UserIdAndYear>();// 执行添加的人员ID
		// 读取excel
		sheet = excelUtils.readFile(in);
		if (sheet != null) {
			// 读取人员ID的Map集合
			Map<String, String> userIDs = new HashMap<String, String>();
			userIDs = trainingClassDao.getUserIDInfo();
			// 读取行
			List<ExcelRow> rowList = sheet.getRowList();
			// 第一行是标题，从第二行开始读取
			for (int i = 1; i < rowList.size(); i++) {
				ExcelRow row = rowList.get(i);
				try {
					List<ExcelCell> cellList = row.getCellList();
					// ExcelCell excelCell=null;
					String key = "";
					// for(int f=0;f<cellList.size();f=f+3) {
					int startYear = 0;
					// excelCell=cellList.get(f);
					key = cellList.get(0).getCellValue().toString();
					key = key + "+" + cellList.get(1).getCellValue().toString();
					startYear = Integer.parseInt(cellList.get(2).getCellValue().toString());
					// 通过姓名+出生年月在Map集合中找到这个人的userID
					String userId = userIDs.get(key);

					if (userId != null) {
						// 人员ID不为空的可以执行添加操作
						for (int z = startYear; z <= 2013; z++) {
							UserIdAndYear uy = new UserIdAndYear();
							uy.setUserID(userId);
							uy.setStartYear(z);
							doUserIDs.add(uy);
						}
					} else {
						// 未执行添加的人员
						notDoUserIDs.add(key);
					}
					// }
				} catch (Exception e) {
					msg = "第" + row.getRowNum() + "行记录导入出错！" + "错误原因：" + e.getMessage();
				}
			}
			// 执行添加操作
			trainingClassDao.addUserOnLineInfoByExcel(doUserIDs);
		}

		if (in != null && !"".equals(in)) {
			in.close();
		}
		return msg;
	}

	/*
	 * 拼凑班级的默认信息
	 */
	public TrainingClass buildTrainingClass(TrainingClass trainingClass) {
		// 全名称
		// 创建培训班的默认信息
		// trainingClass.setClassnamePeriodType("005");//表示期数“无”

		trainingClass.setClassnameUnit("房山区");

		trainingClass.setClassMainName(trainingClass.getClassnameYear() + "年" + trainingClass.getClassnameUnit() + trainingClass.getClassName());// 班级全名称

		trainingClass.setClassUserNum(-1);// 班级人数

		BaseData classType = new BaseData();
		classType.setDataCode("pxblxqt");
		trainingClass.setClassType(classType);// 培训班类型

		BaseData trainingType = new BaseData();
		trainingType.setDataCode("qt");

		BaseData timeUnit = new BaseData();
		timeUnit.setDataCode("pxxs");

		BaseData trainingOrganization = new BaseData();
		trainingOrganization.setDataCode("qtpxjg");

		BaseData beoffCode = new BaseData();
		beoffCode.setDataCode("btclg");

		BaseData applyWay = new BaseData();
		applyWay.setDataCode("dmtx");
		trainingClass.setApplyWay(applyWay);// 报名方式

		BaseData classDescription = new BaseData();
		classDescription.setDataCode("zzllpx");

		BaseData organizerType = new BaseData();
		organizerType.setDataCode("swzzb");

		trainingClass.setPublishState(1);// 发布状态
		trainingClass.setActiveState(1);
		trainingClass.setCreateDate(new Date());
		trainingClass.setOpenState(1);// 开班状态
		trainingClass.setEndState(1);// 结班状态
		trainingClass.setAuditState(1);// 项目审批状态
		return trainingClass;
	}

	/*
	 * 把创建的好的班级信息和班级人员集合执行添加操作 by Max at 2014-5-14
	 */
	public void addTraingInfoByExcel(TrainingClass trainingClass, List<String> userIDs) throws Exception {

		TrainingClassValidCommond commond = new TrainingClassValidCommond(trainingClass);
		// BeanUtils.copyProperties(trainingClass, tclass);
		// 执行添加班级的操作 获取出班级ID
		// trainingClassDao.addTrainingClassByExcel(tclass);
		this.save(commond);

		TrainingClass tclass = (TrainingClass) commond.toEntity();
		// 执行添加人员操作
		trainingClassDao.addUserByExcel(tclass, userIDs);
	}

	/**
	 * 获取这一年中培训班最大的编号
	 * 
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-09
	 */
	@Override
	public String getTrainingNum(TrainingClassValidCommond vCommond) throws Exception {
		Calendar a = Calendar.getInstance();

		Integer year = a.get(Calendar.YEAR);
		// if(year==2014) {
		// year=2015;
		// }
		//
		// if(year.equals(2014)) {
		// year=2015;
		// }
		//
		// if(year.equals("2014")) {
		// year=2015;
		// }
		vCommond.setCurrYear(year + "");// 得到当前年

		/*
		 * Map<String,List<BaseData>> baseDataMap =
		 * baseDataCacheUtil.getBaseDataList(); List<BaseData> baseDataList =
		 * baseDataMap.get(TrainingClass.TRAINING_DEPT); for(BaseData
		 * bd:baseDataList) {
		 * if(bd.getDataCode().equals(vCommond.getTrainingDeptId())) {
		 * vCommond.setTrainingDeptCode(bd.getDataName()); } }
		 */

		String result = trainingClassDao.getTrainingNum(vCommond);
		if (result.equals("empty")) {
			return year + "001";
		} else {
			Integer num = Integer.parseInt(result) + 1;
			return num + "";
		}
	}

	/**
	 * 获取班级下的课程
	 * 
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-11
	 */
	@Override
	public boolean getCourseNum(TrainingClassQueryCommond queryCommond) throws Exception {
		ClassCourseQueryCommond qCommond = new ClassCourseQueryCommond();
		qCommond.setSearchClassIds(queryCommond.getSearchUpdateClassIds());
		List<ClassCourseQueryBean> resultList = classCourseService.findCourseNum(qCommond);
		if (resultList != null && resultList.size() == queryCommond.getSearchUpdateClassIds().length) {
			return true;
		}
		return false;
	}

	/*
	 * 审核操作
	 */
	@Override
	public void updateClassAuditState(TrainingClassQueryCommond qCommond) throws Exception {

		TrainingClassPartFieldUpdateBean trainingClassPartFieldUpdateBean = new TrainingClassPartFieldUpdateBean();
		TrainingClassValidCommond trainingClassValidCommond = new TrainingClassValidCommond();
		trainingClassPartFieldUpdateBean.setiQueryCommond(qCommond);
		String submintType = qCommond.getSubmintType();

		if (TrainingConstants.IS_AUDIT_CLASS_Y.equals(submintType)) {
			trainingClassValidCommond.setAuditState(TrainingClass.IS_AUDIT_Y);
			trainingClassValidCommond.setAuditDate(new Date());
			trainingClassPartFieldUpdateBean.setiCommond(trainingClassValidCommond);
			// 修改专题班的审核状态
			this.updateTrainingClassState(trainingClassPartFieldUpdateBean);
		} else {
			trainingClassValidCommond.setAuditState(TrainingClass.IS_AUDIT_N);
			trainingClassValidCommond.setAuditDate(new Date());
			trainingClassPartFieldUpdateBean.setiCommond(trainingClassValidCommond);
			// 修改专题班的审核状态
			this.updateTrainingClassState(trainingClassPartFieldUpdateBean);
		}

		// 添加审核信息
		List<ClassAuditInfoValidCommond> list = new ArrayList<ClassAuditInfoValidCommond>();
		for (int i = 0; i < qCommond.getSearchUpdateClassIds().length; i++) {
			ClassAuditInfoValidCommond auditCommond = new ClassAuditInfoValidCommond();
			auditCommond.setAduitState(trainingClassValidCommond.getAuditState());
			auditCommond.setAuditReason(qCommond.getAuditReason());
			User user = new User();
			user.setUserId(qCommond.getAuditUserId());
			auditCommond.setCreateUser(user);
			TrainingClass trainingClass = new TrainingClass();
			trainingClass.setClassId(qCommond.getSearchUpdateClassIds()[i]);
			auditCommond.setTrainingClass(trainingClass);
			auditCommond.setCreateDate(new Date());
			list.add(auditCommond);
		}
		classAuditInfoDao.addAuditInfos(list);
	}

	/**
	 * 更新培训班信息
	 * 
	 * @param commond
	 * @throws Exception
	 * @author Max
	 * @date 2014-12-15
	 */
	@Override
	public String updateClassForGW(TrainingClassValidCommond vCommond) throws Exception {
		TrainingClass trainClass = trainingClassDao.find(TrainingClass.class, vCommond.getClassId());
		// 更新前班级信息 by NingSS at 20150505
		String preTrainClass = trainClass.toString();
		trainClass.setClassUserNum(vCommond.getClassUserNum());// 班级人数
		Map<String, BaseData> baseDataMap = baseDataCacheUtil.getBaseData();
		if (PropertyUtil.objectNotEmpty(vCommond.getClassType())) {

			if (vCommond.getClassType().equals("ptb")) {
				// 如果是普通班级，需要删除所有班级单位关系
				ClassDeptValidCommond cdvCommond = new ClassDeptValidCommond();
				cdvCommond.setSearchClassId(vCommond.getClassId());
				classDeptService.delDeptByClassId(cdvCommond);
			}

			// 如果修改了班级类型 删除班级单位关系
			if (trainClass.getClassType() != null) {
				if (!vCommond.getClassType().equals(trainClass.getClassType().getDataCode())) {
					ClassDeptValidCommond cdvCommond = new ClassDeptValidCommond();
					cdvCommond.setSearchClassId(vCommond.getClassId());
					classDeptService.delDeptByClassId(cdvCommond);
				}
			}
			BaseData b = baseDataMap.get(vCommond.getClassType());
			trainClass.setClassType(b);
		}

		if (PropertyUtil.objectNotEmpty(vCommond.getEnterBeginTimeStr())) {
			trainClass.setEnterBeginTime(DateUtil.getDateByString(vCommond.getEnterBeginTimeStr(), "yyyy-MM-dd"));
		}
		if (PropertyUtil.objectNotEmpty(vCommond.getEnterEndTimeStr())) {
			trainClass.setEnterEndTime(DateUtil.getDateByString(vCommond.getEnterEndTimeStr(), "yyyy-MM-dd"));
		}
		trainClass.setPerfectState(TrainingClass.PERFECTSTATE_Y);// 已完善
		trainClass = decideSignState(vCommond, trainClass);
		this.getDaoSupport().update(trainClass);
		// 添加记录日志的逻辑 add by NingSS at 20150504
		LogRecord logRecord = new LogRecord();
		LogRecordParam paramChild = new LogRecordParam();
		paramChild.setOpdataId(trainClass.getClassId());// 操作主数据id
		paramChild.setOpbefoData(preTrainClass);// 操作前数据
		paramChild.setOpafteData(trainClass.toString());// 操作后数据
		paramChild.setOpmodule("工委 - 工委完善培训班 - 维护培训班");// 操作模块
		paramChild.setOpcontent("完善培训班信息");// 操作说明
		paramChild.setOptype(UniteConstants.UPDATE); // 操作类型
		logRecord.bulifLogParams(paramChild);
		try {
			LogThread logThread = new LogThread(paramChild);
			Thread thread = new Thread(logThread);
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// TODO 还缺少报名逻辑的操作
		return "";
	}

	/**
	 * 更新班级表学时
	 * 
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-15
	 */
	@Override
	public void updateStudyHour(Double hour, String classId) throws Exception {
		trainingClassDao.updateStudyHour(hour, classId);
	}

	@Override
	public List<TrainingClassQueryBean> findThematicClassListNoPage(TrainingClassQueryCommond commond) throws Exception {

		return trainingClassDao.findTrainingClassListNoPage(commond);
	}

	/*
	 * 根据时间去判断报名状态
	 */
	public TrainingClass decideSignState(TrainingClassValidCommond commond, TrainingClass trainClass) throws Exception {
		if (trainClass.getEnterBeginTime() != null && trainClass.getEnterEndTime() != null) {
			Date beginDate = trainClass.getEnterBeginTime();
			Date endDate = trainClass.getEnterEndTime();
			Date nowDate = new Date();
			java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
			java.util.Calendar c1 = java.util.Calendar.getInstance();
			java.util.Calendar c2 = java.util.Calendar.getInstance();
			java.util.Calendar c3 = java.util.Calendar.getInstance();
			c1.setTime(df.parse(df.format(beginDate)));
			c2.setTime(df.parse(df.format(endDate)));
			c3.setTime(df.parse(df.format(nowDate)));
			int result1 = c1.compareTo(c3);
			int result2 = c2.compareTo(c3);

			if (result1 == 0) {
				// 开始报名
				trainClass.setSignUpState(TrainingClass.IS_SIGNUP_BEGIN);
			} else if (result1 < 0) {
				if (result2 < 0) {
					// 报名结束
					trainClass.setSignUpState(TrainingClass.IS_SIGNUP_END);
				} else {
					// 开始报名
					trainClass.setSignUpState(TrainingClass.IS_SIGNUP_BEGIN);
				}
			} else {
				// 未开始报名
				trainClass.setSignUpState(TrainingClass.IS_SIGNUP_N);
			}
		}
		return trainClass;
	}

	/**
	 * 获取班级下的的学员数量
	 * 
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-29
	 */
	@Override
	public boolean getStudentNum(TrainingClassQueryCommond queryCommond) throws Exception {
		ClassUserQueryCommond qCommond = new ClassUserQueryCommond();
		qCommond.setSearchClassIds(queryCommond.getSearchUpdateClassIds());
		List<ClassUserQueryBean> resultList = classUserDao.findStudentNum(qCommond);
		if (resultList != null && resultList.size() > 0) {
			return false;
		}
		return true;
	}

	/**
	 * 单位报名班级列表
	 * 
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2015-1-5
	 */
	@Override
	public List<TrainingClassQueryBean> findTrainingClassListByDept(TrainingClassQueryCommond queryCommond) throws Exception {
		// 根据报名单位id查询treepath
		SignupDeptQueryCommond signupDeptQueryCommond = new SignupDeptQueryCommond();
		signupDeptQueryCommond.setSearchDepId(queryCommond.getSearchTrainingApplyDeptId());
		List<SignupDeptValidCommond> depts = (List<SignupDeptValidCommond>) signupDeptService.findAllList(signupDeptQueryCommond);
		if (PropertyUtil.objectNotEmpty(depts) && depts.size() > 0) {
			SignupDeptValidCommond signupDept = depts.get(0);
			queryCommond.setSearchTrainingApplyDeptTreepath(signupDept.getTreepath());
			List<TrainingClassQueryBean> list = trainingClassDao.findTrainingClassListByDept(queryCommond);
			return list;
		}
		return null;
	}

	/**
	 * 单位报名班级列表
	 * 
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author GaoGQ
	 * @date 2015-03-26
	 */
	@Override
	public List<TrainingClassQueryBean> findTrainingClassListByDeptFinish(TrainingClassQueryCommond queryCommond) throws Exception {
		// 根据报名单位id查询treepath
		SignupDeptQueryCommond signupDeptQueryCommond = new SignupDeptQueryCommond();
		signupDeptQueryCommond.setSearchDepId(queryCommond.getSearchTrainingApplyDeptId());
		List<SignupDeptValidCommond> depts = (List<SignupDeptValidCommond>) signupDeptService.findAllList(signupDeptQueryCommond);
		if (PropertyUtil.objectNotEmpty(depts) && depts.size() > 0) {
			SignupDeptValidCommond signupDept = depts.get(0);
			queryCommond.setSearchTrainingApplyDeptTreepath(signupDept.getTreepath());
			List<TrainingClassQueryBean> list = trainingClassDao.findTrainingClassListByDeptFinish(queryCommond);
			return list;
		}
		return null;
	}

	/**
	 * 查询单位培训班没有分页
	 * 
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年1月15日
	 */
	public List<TrainingClassQueryBean> findTrainingClassListByDeptNoPage(TrainingClassQueryCommond queryCommond) throws Exception {
		// 根据报名单位id查询treepath
		SignupDeptQueryCommond signupDeptQueryCommond = new SignupDeptQueryCommond();
		signupDeptQueryCommond.setSearchDepId(queryCommond.getSearchTrainingApplyDeptId());
		List<SignupDeptValidCommond> depts = (List<SignupDeptValidCommond>) signupDeptService.findAllList(signupDeptQueryCommond);
		if (PropertyUtil.objectNotEmpty(depts) && depts.size() > 0) {
			SignupDeptValidCommond signupDept = depts.get(0);
			queryCommond.setSearchTrainingApplyDeptTreepath(signupDept.getTreepath());
			List<TrainingClassQueryBean> list = trainingClassDao.findTrainingClassListByDeptNoPage(queryCommond);
			return list;
		}
		return null;
	}

	/**
	 * 个人报名 可报名班级列表
	 * 
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年1月11日
	 */
	@Override
	public List<TrainingClassQueryBean> findUserSignupClassList(TrainingClassQueryCommond queryCommond) throws Exception {
		PreAuthorizationRegistrationQueryCommond preAuthorizationRegistrationQueryCommond = new PreAuthorizationRegistrationQueryCommond();
		preAuthorizationRegistrationQueryCommond.setSearchUserId(queryCommond.getSearchUserId());
		List<PreAuthorizationRegistrationValidCommond> preList = (List<PreAuthorizationRegistrationValidCommond>) preAuthorizationRegistrationService
				.findList(preAuthorizationRegistrationQueryCommond);
		if (PropertyUtil.objectNotEmpty(preList) && preList.size() > 0) {
			queryCommond.setIsAuthorization(TrainingClassQueryCommond.IS_AUTHORIZATION_Y);
		} else {
			queryCommond.setIsAuthorization(TrainingClassQueryCommond.IS_AUTHORIZATION_N);
		}
		// queryCommond.setSearchClassType(TrainingClass.PTB_CLASS_TYPE);//班级类型普通班
		List<TrainingClassQueryBean> trainignClassList = trainingClassDao.findUserSignupClassList(queryCommond);
		return trainignClassList;
	}

	/**
	 * 更新状态
	 * 
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-15
	 */
	@Override
	public void updateCState(String classId) throws Exception {
		trainingClassDao.updateCState(classId);
	}

	@Override
	public List<TrainingClassQueryBean> queryTrainingClassList(TrainingClassQueryCommond qCommond) throws Exception {
		// TODO Auto-generated method stub
		return trainingClassDao.queryTrainingClassList(qCommond);
	}

	/**
	 * 返回传入日期与当前日期的比较结果(精确到分),小于为-1,等于为0,大于为1
	 * 
	 * @param date
	 * @author LongJZ
	 * @return
	 */
	public int compare_date(Date date) {
		java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
		Date nDate = new Date();
		try {
			return df.parse(df.format(date)).compareTo(df.parse(df.format(nDate)));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return -2;
	}
	
	/**
	 * 返回传入日期与当前日期的比较结果(精确到分),小于为-1,等于为0,大于为1
	 * 
	 * @param date
	 * @author LongJZ
	 * @return
	 */
	public int compare_date_end(Date date) {
		java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
		Date nDate = new Date();
		try {
			return df.parse(df.format(date)).compareTo(df.parse(df.format(nDate)));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return -2;
	}

	/**
	 * 根据当前时间更新班级的开班及报名状态
	 * 
	 * @throws Exception
	 * @author LongJZ
	 * @createDate 2016-1-12
	 * @return
	 */
	public String updateOpenAndSignUpState(TrainingClassQueryCommond commond) throws Exception {
		List<TrainingClassValidCommond> classList = (List<TrainingClassValidCommond>) this.findAllList(commond);
		for (TrainingClassValidCommond classBean : classList) {
			/*
			 * 添加班级状态和报名状态的判断: 1、只要是未发布的班级状态就是未开班 2、只要是未发布的报名状态就是未开始报名
			 * 3、已发布且已开班的报名状态就是报名结束
			 */
			if (PropertyUtil.objectNotEmpty(classBean.getPublishState()) && (TrainingClass.IS_PUBLISH_N == classBean.getPublishState())) {// 未发布
				// 未开班
				classBean.setOpenState(TrainingClass.IS_OPENSTATE_N);
				// 报名未开始
				classBean.setSignUpState(TrainingClass.IS_SIGNUP_N);

			} else {// 已发布
					// 班级状态判断
					// 已结班
				if (PropertyUtil.objectNotEmpty(classBean.getEndDate()) && compare_date(classBean.getEndDate()) < 0){
					classBean.setOpenState(TrainingClass.IS_ENDSTATE_Y);
				}
				// 已开班
				else if (PropertyUtil.objectNotEmpty(classBean.getBeginDate()) && compare_date(classBean.getBeginDate()) <= 0)
					classBean.setOpenState(TrainingClass.IS_OPENSTATE_Y);
				// 未开班
				else if (PropertyUtil.objectNotEmpty(classBean.getBeginDate()) && compare_date(classBean.getBeginDate()) > 0)
					classBean.setOpenState(TrainingClass.IS_OPENSTATE_N);
				else
					classBean.setOpenState(null);
				// 报名状态判断
				if (PropertyUtil.objectNotEmpty(classBean.getOpenState()) && (TrainingClass.IS_OPENSTATE_Y == classBean.getOpenState()||TrainingClass.IS_ENDSTATE_Y== classBean.getOpenState())) {
					// 报名结束
					classBean.setSignUpState(TrainingClass.IS_SIGNUP_END);
				} else {
					// 报名结束
					if (PropertyUtil.objectNotEmpty(classBean.getEnterEndTime()) && compare_date(classBean.getEnterEndTime()) < 0)
						classBean.setSignUpState(TrainingClass.IS_SIGNUP_END);
					// 正在报名
					else if (PropertyUtil.objectNotEmpty(classBean.getEnterBeginTime()) && compare_date(classBean.getEnterBeginTime()) <= 0)
						classBean.setSignUpState(TrainingClass.IS_SIGNUP_BEGIN);
					// 报名未开始
					else if (PropertyUtil.objectNotEmpty(classBean.getEnterBeginTime()) && compare_date(classBean.getEnterBeginTime()) > 0)
						classBean.setSignUpState(TrainingClass.IS_SIGNUP_N);
					else
						classBean.setSignUpState(null);
				}
			}
			classBean.setLatestOperateDate(new Date());
			trainingClassDao.update(classBean.toEntity());
		}
		return "";
	}

	/**
	 * 判断培训班编号是否一样
	 * 
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2016-1-15
	 */
	@Override
	public boolean decideClassNum(TrainingClassValidCommond commond) throws Exception {
		return this.trainingClassDao.decideClassNum(commond);
	}

	/**
	 * @category 查询班级的报名情况(委托部委办班在线报名系统)
	 * @param validCommond
	 * @throws Exception
	 * @author NingSS
	 * @return
	 */
	@Override
	public List<TrainingClassQueryBean> findClassUserAsignCount(TrainingClassQueryCommond queryCommond) throws Exception {
		return trainingClassDao.findClassUserAsignCount(queryCommond);
	}

	/**
	 * @评估查询
	 * @Name: findClassAssessmentt
	 * @Description: @param qCommond
	 * @Description: @param request
	 * @Description: @param response
	 * @Description: @param resultState
	 * @Description: @return
	 * @Description: @throws Exception
	 * @Author: GUOLEI
	 * @Version: V1.00
	 * @Create Date: 2016-2-6下午12:23:22
	 * @Parameters: ITrainingClassService
	 * @Return: String
	 */
	public List<TrainingClassQueryBean> findClassAssessmentt(TrainingClassQueryCommond qCommond) throws Exception {
		return trainingClassDao.findClassAssessmentt(qCommond);
	}

	/**
	 * @评估人员
	 * @Name: findAnswerUser
	 * @Description: @param queryCommond
	 * @Description: @throws Exception
	 * @Author: RongSL
	 * @Version: V1.00
	 * @Create Date: 2016-2-16
	 * @Return: List<BaseUser>
	 */

	public List<BaseUserBean> findAnswerUser(TrainingClassQueryCommond queryCommond) throws Exception {
		return trainingClassDao.findAnswerUser(queryCommond);
	}

	/**
	 * 查询已评估人员
	 * @createDate 2017-3-2
	 * @author RongSL
	 * */
	@Override
	public
	List<BaseUserBean> findAlreadyEvaluated(TrainingClassQueryCommond queryCommond) throws Exception {
		return trainingClassDao.findAlreadyEvaluated(queryCommond);
	}
	/**
	 * 更新评估时间
	 * 
	 * @param commond
	 * @throws Exception
	 * @author LongJZ
	 * @date 2016-4-18
	 */
	@Override
	public void updateAssessTime(TrainingClassValidCommond commond) throws Exception {
		trainingClassDao.updateAssessTime(commond);
	}

	/**
	 * 新增附件
	 * 
	 * @param commond
	 * @throws Exception
	 * @author RongSL
	 * @date 2016-7-28
	 */
	public BaseAttachment saveBaseAttachment(BaseAttachment bd) {
		return trainingClassDao.saveBaseAttachment(bd);
	}

	/**
	 * 获得培训班考勤率
	 * 
	 * @author RongSL
	 * @Date 2016-09-17
	 * */
	@Override
	public Map<String, Integer> getAttendanceChance(TrainingClassQueryCommond queryCommond) {
		return trainingClassDao.getAttendanceChance(queryCommond);
	}

	/**
	 * @课程评估查询
	 * @Name: findClassAssessmentt
	 * @Author: RongSL
	 * @CreateDate: 2016-5-20
	 * @Return: List<TrainingClassQueryBean>
	 */
	public List<TrainingClassQueryBean> findCourseAssessment(TrainingClassQueryCommond queryCommond) throws Exception {
		return trainingClassDao.findCourseAssessment(queryCommond);
	}

	/**
	 * @课程评估人员
	 * @Name: findCourseAnswerUser
	 * @Description: @param queryCommond
	 * @Description: @throws Exception
	 * @Author: RongSL
	 * @Version: V1.00
	 * @Create Date: 2016-5-30
	 * @Return: List<BaseUser>
	 */
	public List<BaseUserBean> findCourseAnswerUser(TrainingClassQueryCommond queryCommond) throws Exception {
		// return getList(trainingClassDao.findCourseAnswerUser(queryCommond));
		return trainingClassDao.findCourseAnswerUser(queryCommond);
	}

	/**
	 * 解密方法
	 * 
	 * @param list
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author GuoL
	 * @date 2015-5-5
	 */
	public List<BaseUserBean> getList(List<BaseUserBean> list) throws Exception {
		int i = 0;
		for (; i < list.size(); i++) {
			if (list.get(i).getUserName() != null && list.get(i).getUserName() != "") {
				byte[] byteArray = Base64Util.decryptBASE64(list.get(i).getUserName());
				String name = new String(byteArray, "utf-8");
				list.get(i).setUserName(name);
			}
		}
		return list;
	}

	/**
	 * 查询子部门
	 * */
	public List<Department> findDedepartmentList(DepartmentValidCommond validCommond) throws Exception {
		return trainingClassDao.findDedepartmentList(validCommond);
	}

	/**
	 * 获得培训班编号
	 * 
	 * @author RongSL
	 * @date 2017-01-07
	 * */
	public String getTrainingClassNum() {
		return trainingClassDao.getTrainingClassNum();
	}

	/**
	 * 保存实体bean
	 * 
	 * @author RongSL
	 * @date 2017-01-08
	 * */
	public <T extends AbstractBaseEntity & IBaseEntity> void saveEntity(T view) {
		trainingClassDao.saveEntity(view);
	}

	@Override
	public User findByLoginID(String loginID) {
		// TODO Auto-generated method stub
		return trainingClassDao.findByLoginID(loginID);
	}

	@Override
	public String saveClassUser(TrainingClass tc, User user) {
		// TODO Auto-generated method stub
		boolean flag = trainingClassDao.findClassUser(tc, user);
		if (flag) {
			String msg = "已报名";
			return msg;
		} else {
			ClassUser classUser = new ClassUser();
			classUser.setTrainingClass(tc);
			classUser.setUser(user);
			classUser.setTrainingHours(0.0);
			classUser.setAuditingState(ClassUser.NO_AUDITING);
			classUser.setUserName(user.getUserName());
			classUser.setSexCode(user.getSexCode());
			classUser.setFolkCode(user.getFolkCode());
			classUser.setBirthday(user.getBirthday());
			classUser.setRemark(user.getRemark());
			classUser.setDutyRemark(user.getDutyRemark());
			classUser.setMobileTelephone(user.getMobileTelephone());
			trainingClassDao.save(classUser);
			return "";
		}
	}

	@Override
	public TrainingClass findByClassId(String classId) {
		// TODO Auto-generated method stub
		TrainingClass tc = trainingClassDao.findByClassId(classId);
		/*
		 * if(tc.getPublishState()==TrainingClass.IS_PUBLISH_Y&&tc.getSignUpState
		 * ()==TrainingClass.IS_SIGNUP_BEGIN){ return
		 * trainingClassDao.findByClassId(classId); }else{ return null; }
		 */
		return tc;
	}

	@Override
	public int findRoleForScope(String deptId, String classNum) {
		// TODO Auto-generated method stub
		return trainingClassDao.findRoleForScope(deptId, classNum);
	}

	/**
	 * 查询是否有被市委组织部选为承办部委
	 * 
	 * @author RongSL
	 * @Date 2017-01-19
	 * */
	public int isGJCChoiceUndertake(String depId) {
		return trainingClassDao.isGJCChoiceUndertake(depId);
	}
	
	/**
	 * 批量更新问卷评估方式
	 * @author RongSl
	 * @Date 2017-02-13
	 * */
	@Override
	public void updateQuestionnaireMethod(TrainingClassQueryCommond queryCommond){
		trainingClassDao.updateQuestionnaireMethod(queryCommond);
	}
	
	//查询二级节点上的第一个一级节点 by RongSL 20170705
	public List<?> findAdminLevel(DepartmentTreeCondition condition) throws Exception{
		return trainingClassDao.findAdminLevel(condition);
	}
	
	@Override
	public List<TrainingClassQueryBean> findAuditTrainingClassList(
			TrainingClassQueryCommond commond) throws Exception {
		List<TrainingClassQueryBean> list = null;
//		String[] ids = this.trainingClassDao.findTrainingClassLockStateIds(commond);
//		if(PropertyUtil.objectNotEmpty(ids) && ids.length >0){
//			commond.setSearchClassIds(ids);
			list = this.trainingClassDao.findAuditTrainingClassList(commond);
			if(list!=null&&list.size()>0) {
				String classIds = "";
				for (TrainingClassQueryBean trainingClassQueryBean : list) {
					if(trainingClassQueryBean.getStartDateState() != null || trainingClassQueryBean.getEndDateState()!=null){
						if(Integer.parseInt(trainingClassQueryBean.getStartDateState()) >= 0 && Integer.parseInt(trainingClassQueryBean.getEndDateState()) <= 0){
							//在确认时间范围内
							trainingClassQueryBean.setLockDateState(1);
						}else{
							//不在确认时间范围内
							trainingClassQueryBean.setLockDateState(2);
						}
					}else{
						trainingClassQueryBean.setLockDateState(1);
					}
					classIds += ",'"+trainingClassQueryBean.getClassId()+"'";
				}
				classIds = classIds.substring(1);
				commond.setSearchClassId(classIds);
				List<TrainingClassQueryBean> list2=trainingClassDao.findClassNum(commond);
				for (int i = 0; i < list.size(); i++) {
					TrainingClassQueryBean bean = list.get(i);
					for (int j = 0; j < list2.size(); j++) {
						TrainingClassQueryBean bean2 = list2.get(j);
							if(bean.getClassId().equals(bean2.getClassId())){
	//						bean.setReportedNum(bean2.getReportedNum());
	//						bean.setReportedNumber(bean2.getReportedNumber());
	//						bean.setShiguanNum(bean2.getShiguanNum());
	//						bean.setAuditShiguanNum(bean2.getAuditShiguanNum());
							bean.setLockNum(bean2.getLockNum());
							bean.setTrainingClassSum(bean2.getTrainingClassSum());
							bean.setTrainingClassAvg(bean2.getTrainingClassAvg());
							bean.setNoClassUserNum(bean2.getNoClassUserNum());
						}
					}
				}
			}
//		}
		return list;
	}
	
	/**
	 * 查询培训班(归档数据)
	 * @author RongSL
	 * 2017年12月22日
	 * */
	public TrainingClassValidCommond findTrainingPxarchives(TrainingClassValidCommond vCommond){
		return this.trainingClassDao.findTrainingPxarchives(vCommond);
	}
}
